package com.yoomiito.app.ui.order.sureorder.singleGoods

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.FrameLayout
import com.yoomiito.app.Constant
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.bean.AddressInfo
import com.yoomiito.app.model.bean.GoodsDetail
import com.yoomiito.app.model.order.NewCreateOrderData
import com.yoomiito.app.model.order.OrderingInfo
import com.yoomiito.app.model.order.ShopCarGoods
import com.yoomiito.app.model.sdd.SddFreeGoodsData
import com.yoomiito.app.pay.OrderPayInfo
import com.yoomiito.app.pay.PayResult
import com.yoomiito.app.pay.PayUtilsManager
import com.yoomiito.app.ui.anyview.sureorder.bottom.BaseSureOrderBottomView
import com.yoomiito.app.ui.anyview.sureorder.bottom.SureOrderBottomView
import com.yoomiito.app.ui.anyview.sureorder.header.BaseSureOrderHeaderView
import com.yoomiito.app.ui.anyview.sureorder.header.SureOrderGoodsIncludeSizeView
import com.yoomiito.app.ui.anyview.sureorder.header.SureOrderGoodsView
import com.yoomiito.app.ui.order.sureorder.BuyResultActivity
import com.yoomiito.app.ui.songduoduo.freegoods.StatusOfFreeGoodsActivity
import com.yoomiito.app.utils.*
import kotlinx.android.synthetic.main.act_new_sure_order.*
import kotlinx.android.synthetic.main.title_bar.*

class NewSureOrderActivity :BaseActivity<NewSureOrderPresenter>(){

    companion object{
        fun start(context: Context,goodsDetail: GoodsDetail){
            val intent = Intent(context,NewSureOrderActivity::class.java)
            intent.putExtra(Const.Common.Data,goodsDetail)
            context.startActivity(intent)
        }
    }
    private var goodsType = 0
    private lateinit var goodsDetail:GoodsDetail
    private lateinit var orderHeaderView:BaseSureOrderHeaderView
    private lateinit var bottomView: BaseSureOrderBottomView
    private var mQueryOrderID = ""
    private var mDeductMoneyPay = 0
    private var mGoodsSize = 1

    override fun getLayoutId(): Int = R.layout.act_new_sure_order

    override fun newP(): NewSureOrderPresenter= NewSureOrderPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        title_bar.setBackgroundColor(ResUtil.getColor(R.color.color_gray_F8F8F8))
        tv_center.text="确认订单"
        iv_back_left.setOnClickListener { finish() }
        goodsDetail = intent.getSerializableExtra(Const.Common.Data) as GoodsDetail
        goodsType = DataUtils.getGoodsType(goodsDetail.good_type, goodsDetail.product_type)
        initContent()
        initBottomView()
        showLoading()
        p.getAddress()
    }

    private fun initContent() {
        orderHeaderView = when(goodsType){
            Type.GoodsType.GiveMore-> SureOrderGoodsIncludeSizeView(this,goodsDetail)
            Type.GoodsType.FreeGift-> SureOrderGoodsView(this, goodsDetail)
            else -> SureOrderGoodsView(this, goodsDetail)
        }
        val lp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT)
        frameLayout.addView(orderHeaderView,lp)
        orderHeaderView.onShowListener = {spanText, goodsSize, yoMoneyPay ->
            mDeductMoneyPay = yoMoneyPay
            mGoodsSize = goodsSize

        }
    }

    private fun initBottomView() {
        bottomView = when(goodsType){
            Type.GoodsType.FreeGift->{
                SureOrderBottomView(this)
            }
            Type.GoodsType.GiveMore->{
                SureOrderBottomView(this)
            }
            else->{
                SureOrderBottomView(this)
            }
        }
        val lp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT)
        bottomParentView.addView(bottomView,lp)
        bottomView.onClickListener={
            showLoading()
            when(goodsType){
                Type.GoodsType.FreeGift->{
                    p.createSddOrder(NewCreateOrderData(orderHeaderView.addressInfo(), listOf(ShopCarGoods(goodsDetail.num_iid,1,orderHeaderView.msg()))))
                }
                else ->{
                    p.createOrder(NewCreateOrderData(orderHeaderView.addressInfo(), listOf(ShopCarGoods(goodsDetail.num_iid,1,orderHeaderView.msg()))))
                }
            }
        }
    }

    fun showAddressView(addressInfo: AddressInfo){
        dismissLoading()
        orderHeaderView.updateAddressInfo(addressInfo)
    }

    /**
     * 送多多--赠品创建订单结果
     */
    fun createOrderSuccess(data: SddFreeGoodsData){
        StatusOfFreeGoodsActivity.start(this,data)
        finish()
    }

    fun pay(info: OrderPayInfo) {
        dismissLoading()
        info.goodsType = goodsDetail.product_type
        info.moneyPay = orderHeaderView.mGoodsTotalPrice// 订单支付总金额
        info.deductMoneyPay = mDeductMoneyPay//可抵扣余额
        PayUtilsManager.instance .payResultListener = {
            mQueryOrderID = it.queryOrderId
            when(it.payState){
                PayResult.PaySuccess -> {
                    val eventMessage = EventMessage()
                    eventMessage.goodsType = goodsType
                    BuyResultActivity.start(this, eventMessage)
                    finish()
                }
                PayResult.PayFail -> {//支付失败
                    //TODO 支付失败处理
                }
            }
        }
        PayUtilsManager.instance
                .init(this, goodsType)
                .toGeneralPay(info)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (Const.RequestCode.AddressCode == requestCode && data != null) {
            val addressResult = data.getSerializableExtra(Constant.DATA) as AddressInfo
            orderHeaderView.updateAddressInfo(addressResult)
        }
    }


    //获取到微信结果后 查询订单状态
    override fun eventMessage(eventMessage: EventMessage) {
        super.eventMessage(eventMessage)
        if (Constant.PAY_RESULT == eventMessage.eventType) {
            //TODO 支付完成查询订单
            if (TextUtils.isEmpty(mQueryOrderID)) {
                showToast("订单状态异常")
                return
            }
            showLoading()
//            p.queryOrder(mQueryOrderID, pay_type)
        }
    }

    override fun finish() {
        super.finish()
        PayUtilsManager.instance.release()
    }
}